package com.erainm.consumerInterceptors;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.IntegerDeserializer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by erainm on 2021/9/10 5:50 下午.
 *
 * @Description TODO:消费者
 **/
public class MyConsumer {
    public static void main(String[] args) {
        Map<String, Object> configs = new HashMap<>();
        configs.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"lg04:9092");
        // 使用常量代替手写的字符串，配置key的反序列化器
        configs.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        // 配置value的反序列化器
        configs.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        // 配置消费组ID
        configs.put(ConsumerConfig.GROUP_ID_CONFIG,"mygrp");
        configs.put(ConsumerConfig.CLIENT_ID_CONFIG,"myClient");
        // 如果找不到当前消费者的有效偏移量，则自动重制到最开始
        // latest表示直接重制到消息偏移量的最后一个
        configs.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");

        configs.put(ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG,
                    "com.erainm.consumerInterceptors.OneInterceptor" +
                    ",com.erainm.consumerInterceptors.TwoInterceptor" +
                    ",com.erainm.consumerInterceptors.ThreeInterceptor"
                );

        KafkaConsumer<String, String> consumer = new KafkaConsumer<String,String>(configs);

        // 订阅主题
        consumer.subscribe(Collections.singleton("tp_demo_01"));

        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(3000);
            records.forEach(record -> {
                System.out.println(record.topic() + "\t" + record.partition() + "\t" + record.offset() + "\t" + record.key() + "\t" + record.value());
            });
        }
    }
}
